#!/bin/bash
file=$1
binpath=/home/runmngs/CNV_mNGS
prefix=$(basename $file .500k.wig)
  #do prefix=$(basename $file .fastq.gz)
   prefix=$(basename $file .sorted.bam)
  echo -e "\nprocessing $file\n"
  #echo "$prefix"
  # -j 2: 2 cores, -u 25: unconditionally remove the first 25 bases, 
  #cutadapt -j 2 -u 25 -u -1 -q 20 -m 36 -o $prefix.trimmed.fastq.gz $file
  #mapping and bam processing
  #bwa mem -t 4 /data/reference/PGT/hg19.fa "$file" > $prefix.sam
  samtools flagstat $file > $prefix.flagstat
  #samtools view -h -F 4 -q 30 $file | grep -P -v 'chrM|chr.*_.*' - > $prefix.filtered.sam
  samtools view -h -F 4 -q 30 $file |grep "Chr"|grep -v "ChrM" |perl -alne '{if (/^@/){print $_;}else {next if $F[2] eq "ChrMT";if($F[2] =~ m/Chr/g){print $_;}}}' > $prefix.filtered.sam
  samtools sort -O bam -@ 1 $prefix.filtered.sam > $prefix.bam
#  java -jar /data/reference/PGT/bin/picard.jar MarkDuplicates INPUT=$prefix.bam OUTPUT=$prefix.rmdup.bam METRICS_FILE=$prefix.rmdup.metrics REMOVE_DUPLICATES=true
  samtools rmdup $prefix.bam $prefix.rmdup.bam
  samtools index $prefix.rmdup.bam
  samtools flagstat $prefix.rmdup.bam > $prefix.rmdup.flagstat
  rm $prefix.filtered.sam
  rm $prefix.bam

  #HMMcopy
  #/usr/local/bin/hmmcopy_utils/bin/readCounter -w 100000 $prefix.rmdup.bam > $prefix.100k.wig
  $binpath/readCounter -w 500000 $prefix.rmdup.bam > $prefix.500k.wig

rm $prefix.rmdup.bam
rm $prefix.rmdup.bam.bai

/data/softwares/R4.0.4/R-4.0.4_install/bin/Rscript $binpath/run_hmmcopy.hg19_75mer_500k38.r $prefix.500k.wig
perl $binpath/form.pl $prefix.500k.wig.seg $prefix.500k.wig.data.seg >$prefix.500k.bed
Rscript $binpath/cv2.R $prefix.500k.wig.bed

sed -i 's/Chr/chr/g' $prefix.500k.wig.bed

python3 $binpath/ClassifyCNV/ClassifyCNV.py --infile $prefix.500k.wig.bed --GenomeBuild hg38 --precise --outdir $prefix

python3 $binpath/formcytoband.py $binpath/cytoBand_hg38.txt $prefix/Scoresheet.txt >$prefix.result.txt
